<template>
    <div class="rx-vue-tree-box">
        <rx-vue-tree
            class="tree-style"
            :tree-data="treeData"
            :async-tree="async"
            :field="'treeId'"
            :label="'name'"
            :show-checkbox="false"
            :show-edit="edit"
            @expandClick="triggerClick"
            :expandedKeys.sync="expandedKeys"
            @rowClick="handSelect"
            :tree-icon="treeIcon"
            :show-icon="true"
            :iconStyle="{fontSize:'13px',backgroundColor:'transparent',color:'#333'}"
        >
            <div slot="edit" slot-scope="{tree,data}">
                <div class="btn" @click="addNode(tree,data)"><a-icon type="plus" />
                    {{i18n('node.addChildNodes','新增子节点') }}
                </div>
                <div class="btn" v-if="tree.treeId == '0' &&isAdmin" @click="showAuthList"><a-icon type="setting" />
                    {{i18n('node.authorization','授权管理') }}
                </div>
                <div class="btn" v-if="isAdmin && tree.treeId != '0'" @click="grantNode(tree,data)"><a-icon type="setting" />
                    {{i18n('node.controlPower','控制权限') }}</div>
                <div class="btn" v-if="tree.treeId != '0'" @click="addSibling(tree,data)"><a-icon type="plus" />
                    {{i18n('node.addSibling','添加同级') }}</div>
                <div class="btn" v-if="tree.treeId != '0'" @click="editNode(tree,data)"><a-icon type="edit" />
                    {{i18n('node.editNodes','编辑节点') }}</div>
                <div class="btn del" v-if="tree.treeId != '0'" @click="deleteNode(tree,data)"><a-icon type="delete" />
                    {{i18n('node.deleteNodes','删除节点') }}</div>
                <div class="btn" v-if="tree.treeId != '0' && tree.catKey == 'DIC' && !curApp.appId" @click="share(tree,data)"><a-icon type="share-alt" />
                    {{$ti18('rxList.share','共享')}}</div>
            </div>
        </rx-vue-tree>
    </div>
</template>

<script>
import SysTreeEdit from "../../views/modules/system/core/SysTreeEdit";
import SysAuthSettingTreeEdit from "../../views/modules/system/core/SysAuthSettingTreeEdit";
import SysAuthSettingDialog from "../../views/modules/system/core/SysAuthSettingDialog";
import SysTreeApi from '@/api/system/core/sysTree'
import {Util, RxVueTree,Dialog} from "@lowcode/jpaas-common-lib";
import tree from './mixin/tree'
import FormResourceShareApi from "@/api/form/core/formResourceShare";
import {mapState} from 'vuex';

export default {
    name: "rx-category-treeeditor",
    mixins:[tree],
    props: {
        /**
         * 分类KEY
         */
        catKey: {
            type: String
        },
        /**
         * 权限KEY
         */
        readKey: {
            type: String,
            default: 'read'
        },
        /**
         * 是否管理员,默认管理
         */
        isAdmin: {
            type: Boolean,
            default: true
        },
        /**
         * 默认需要授权。
         */
        isGrant: {
            type: Boolean,
            default: true
        },
        /**
         *  异步属性，默认为true
         */
        async: {
            type: Boolean,
            default: true
        },
        /**
         * 是否允许编辑，默认为true。
         */
        edit: {
            type: Boolean,
            default: true
        },
        /**
         * 初始化的时候进行加载，默认为true
         */
        initOnLoad: {
            type: Boolean,
            default: true
        },
        /**
         *  统计配置
         *  配置结构如下
         *  {
         *       //1.统计的表名
         *      //1.1.简单的表名，如：sys_app
         *      //1.2.带数据库前缀的表名，如果该表不是在jpaas_system库中，则需指定表所在的数据库，如：jpaas_bpm.bpm_def
         *      //1.3.多表关联，示例：jpaas_bpm.BPM_TASK t LEFT JOIN jpaas_bpm.bpm_def v ON t.def_id_ = v.def_id_
         *      //1.4.复杂sql，示例：(SELECT t.*, d.APP_ID_ FROM jpaas_bpm.BPM_TASK t
         *                              LEFT JOIN jpaas_bpm.bpm_def d ON t.def_id_ = d.def_id_
         *                              WHERE ASSIGNEE_ = #{w.curUserId} AND t.TENANT_ID_ = #{w.curTenantId} AND t.STATUS_ != 'COMPLETED'
         *                              AND t.STATUS_ != 'LOCKED' UNION SELECT t.*, d.APP_ID_
         *                              FROM jpaas_bpm.bpm_task t LEFT JOIN jpaas_bpm.bpm_def d ON t.def_id_ = d.def_id_
         *                              LEFT JOIN jpaas_bpm.bpm_task_user u ON t.TASK_ID_ = u.TASK_ID_
         *                              WHERE t.ASSIGNEE_ IS NULL AND t.STATUS_ != 'COMPLETED' AND t.STATUS_ != 'LOCKED'
         *                              AND (u.USER_ID_ = #{w.curUserId} AND t.TENANT_ID_ = #{w.curTenantId} OR u.GROUP_ID_ IN (#{w.curUserRoles}))
         *                            ) t
         *      table:"jpaas_form.FORM_PC",
         *      //2.统计的表的参数
         *      //2.1.这里配合带有参数的sql统计表使用
         *      //2.2.name 参数名
         *      //2.3.type:string/number/date 字符、数字、日期
         *      //2.4.dateFormat: 如type为date，必填，其它为空
         *      //2.5.value: 值
         *      //2.6.valueType 取值类型，该项可以不填，默认为specify
         *      //2.6.1.specify：指定类型，也就是value属性定义的值
         *      //2.6.2.context：上下文类型,目前能使用的有如下几种： 1.curUserId【当前用户id】,
         *      //         2.curTenantId【当前机构id】,3.curDate【当前时间】,4.curUserRoles【当前用户角色列表】
         *      //         这几个选项在vaule中填写
         *      //2.7.需特别注意，如果此次指定参数名，上面的table后面的参数必须以#{}进行占位，并且里面的参数要以固定的w.开头，如：#{w.curUserId}
         *      tableParams:[{name:"curUserId", type:"string", dateFormat:"", value:"curUserId", valueType:"context"},
         *                   {name:"curTenantId", type:"string", dateFormat:"",value:"curTenantId", valueType:"context"},
         *                   {name:"curUserRoles", type:"string", dateFormat:"",value:"curUserRoles", valueType:"context"},
         *                   ],
         *      //3.统计表的分类ID字段
         *      //3.1不加表别名前缀，如：CATEGORY_ID_
         *      //3.2加表别名前缀，如：t.CATEGORY_ID_
         *      field:"CATEGORY_ID_",
         *      //4.查询条件
         *      //4.1.其值为对象数组，有则填写，无则为[]
         *      //4.2.name 字段名
         *      //4.3.type:string/number/date 字符、数字、日期
         *      //4.4.dateFormat: 如type为date，必填，其它为空
         *      //4.5.op 操作: =,!=,like,in,>=、<=等
         *      //4.6.value: 指定的值
         *      //4.7.7.valueType 取值类型，该项可以不填，默认为specify
         *      //4.7.7.1 specify：指定类型，也就是value属性定义的值
         *      //4.7.7.2 context：上下文类型,目前能使用的有如下几种： 1.curUserId【当前用户id】,
         *      //         2.curTenantId【当前机构id】,3.curDate【当前时间】
         *      //         这几个选项需在3.6.vaule中填写
         *      whereConf:[{name:"IS_DIALOG_",type:"date",dateFormat:"yyyy-MM-dd HH:mm:ss",op:"=",value:"2020-01-02",valueType:"specify"}]
         *  }
         */
        statisticConfig: {
            type: Object,
            default: ()=>{
                return {}
            }
        },
        treeRootList:{
            type: Array,
            default: ()=>{
                return []
            }
        },
        /**
         * 初始化的时候进行加载，默认为false
         */
        isBpmClient: {
            type: Boolean,
            default: false
        },
        /**
         * 初始化的时候进行加载，默认为false
         */
        isMyBpm: {
            type: Boolean,
            default: false
        },
        /**
         * 流程设计列表新增分类表示
         */
        isBpmDefList:{
            type: Boolean,
            default: false
        },
        /**
         * 分类删除时是否校验关联表有数据
         * 有数据不允许删除
         */
        checkToDel:{
            type: Boolean,
            default: false
        },
    },
    components: {
        RxVueTree
    },
    data() {
        return {
            isTreeCat: true,
            treeIcon:{
                expand:'iconwenjianziliao',
                collapse:'iconfile-folder-fill',
                leaf:'iconfile-text-fill'
            }
        }
    },
    computed: {
        ...mapState({
            user: (state) => state.appSetting.user
        })
    },
    created() {

    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"redxunLang",key);
        },
        handSelect(tree,parentData) {
            this.$emit("handSelect", tree);
        },
        showAuthList(){
            var conf = {
                component: SysAuthSettingDialog,
                title: this.i18n('node.powerList','查看权限配置列表') ,
                widthHeight: ['1000px', '600px'],
                "curVm": this,
                "data": {"catKey": this.catKey}
            };
            Util.open(conf, function (action) {
            });
        },
        addNode(tree,treeData) {
            let data = {
                catKey:tree.catKey,
                parentId:tree.treeId,
                parentName:tree.name,
                rightJson:this.getrightJson()
            }
            this.handClick(data,  this.i18n('isNode.addCategory','添加分类'), "addchild",tree);
        },
        //新增节点时，同时新增该节点权限给创建人
        getrightJson(){
            let userId= this.user.userId;
            let userName=this.user.fullName;
            let setting={
                user:{
                    names: userName,
                    values: userId,
                    include: true
                }
            };
            if(this.isBpmDefList){
                let rightJson=[
                    {
                        "id": "1",
                        "type": "task",
                        "typeName": "待办任务权限",
                        "children": [
                            {
                                "id": "5",
                                "parentId": "1",
                                "type": "read",
                                "typeName": "阅读权限",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            }
                        ],
                        "setting": JSON.stringify(setting),
                        "settingName": "用户:"+userName
                    },
                    {
                        "id": "2",
                        "type": "def",
                        "typeName": "流程定义权限",
                        "children": [
                            {
                                "id": "6",
                                "parentId": "2",
                                "type": "read",
                                "typeName": "阅读权限",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "7",
                                "parentId": "2",
                                "type": "start",
                                "typeName": "启动",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "8",
                                "parentId": "2",
                                "type": "add",
                                "typeName": "新建",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "9",
                                "parentId": "2",
                                "type": "design",
                                "typeName": "设计",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "10",
                                "parentId": "2",
                                "type": "delete",
                                "typeName": "删除",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            }
                        ],
                        "setting": JSON.stringify(setting),
                        "settingName": "用户:"+userName
                    },
                    {
                        "id": "3",
                        "type": "inst",
                        "typeName": "流程实例权限",
                        "children": [
                            {
                                "id": "11",
                                "parentId": "3",
                                "type": "read",
                                "typeName": "阅读权限",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "12",
                                "parentId": "3",
                                "type": "intervene",
                                "typeName": "干预",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "13",
                                "parentId": "3",
                                "type": "delete",
                                "typeName": "删除",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            }
                        ],
                        "setting": JSON.stringify(setting),
                        "settingName": "用户:"+userName
                    },
                    {
                        "id": "4",
                        "type": "start",
                        "typeName": "流程发起权限",
                        "children": [
                            {
                                "id": "14",
                                "parentId": "4",
                                "type": "read",
                                "typeName": "阅读权限",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            },
                            {
                                "id": "15",
                                "parentId": "4",
                                "type": "mobileRead",
                                "typeName": "手机阅读权限",
                                "setting": JSON.stringify(setting),
                                "settingName": "用户:"+userName
                            }
                        ],
                        "setting": JSON.stringify(setting),
                        "settingName": "用户:"+userName
                    }
                ];
                return JSON.stringify(rightJson);
            }else{
                let rightJson=[
                    {
                        id:"1",
                        type:"read",
                        typeName:"阅读权限",
                        setting:JSON.stringify(setting),
                        settingName: "用户:"+userName,
                        idx_: Util.randomId(),
                        serial: "1"
                    },
                    {
                        id:"2",
                        type:"add",
                        typeName:"添加权限",
                        setting:JSON.stringify(setting),
                        settingName: "用户:"+userName,
                        idx_: Util.randomId(),
                        serial: "2"
                    },
                    {
                        id:"3",
                        type:"edit",
                        typeName:"编辑权限",
                        setting:JSON.stringify(setting),
                        settingName: "用户:"+userName,
                        idx_: Util.randomId(),
                        serial: "3"
                    },
                    {
                        id:"4",
                        type:"delete",
                        typeName:"删除权限",
                        setting:JSON.stringify(setting),
                        settingName: "用户:"+userName,
                        idx_: Util.randomId(),
                        serial: "4"
                    },
                ];
                return JSON.stringify(rightJson);
            }

        },
        //资源共享
        share(tree,data){
            let self=this;
            FormResourceShareApi.getShareApps(tree.treeId).then(res => {
                let initData=res.data;
                if(!initData){
                    initData=[];
                }
                self.showAppDialog(initData,tree.treeId,tree.alias,tree.name);
                self.$broadCast && self.$broadCast.postMessage('formDesign')
            });
        },
        showAppDialog(initData,resId,resKey,resName){
            Dialog.openSystemAppDialog({
                curVm: this, widthHeight: ['1150px', '735px'],
                data:{initSelected: initData,isDevelopApp:true,isSelectApp:true}
            }, function (self, data) {
                //保存共享信息
                FormResourceShareApi.saveShareApps(data.apps,resId,resKey,resName,"9").then(res => {
                    if (res.success && res.code == 200) {
                    }
                });
            })
        },
        grantNode(tree,treeData) {
            var self_ = this;
            var conf = {
                component: SysAuthSettingTreeEdit,
                title: this.i18n('isNode.addConfiguration','添加权限配置'),
                widthHeight: ['800px', '600px'],
                "curVm": self_,
                "data": {"curRow": tree}
            };
            Util.open(conf, function (action) {
            });
        },
        addSibling(tree,parenData) {
            var title = this.i18n('isNode.addSibling','添加同级');
            if(parenData && !Array.isArray(parenData)){
                let obj = {
                    parentName: parenData.name,
                    parentId: parenData.treeId,
                    catKey: parenData.catKey
                }
                this.handClick(obj, title, "addSibling",parenData)
            }
        },
        editNode(tree,parentData) {
            this.handClick(tree, this.i18n('isNode.editCategory','编辑分类'), "edit",parentData);
        },
        deleteNode(tree,parentData) {
            var {treeId} = tree;
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    SysTreeApi.delByTreeId({treeId: treeId,catKey:self_.catKey,checkToDel:self_.checkToDel}).then(res => {
                        if (res.success && res.code == 200) {
                            let index =  parentData.children.findIndex(obj=>obj.key == tree.key);
                            parentData.children.splice(index,1);
                            self_.treeData = [...self_.treeData];
                        }else {
                            self_.$message.error(res.message);
                        }
                    })
                },
                onCancel() {
                }
            })
        },
        handClick(data, title, operator,parentData) {
            var conf = {
                curVm: this,
                data: {data: data, displayDataShowType: true},
                widthHeight: ['800px', '450px'],
                component: SysTreeEdit,
                title: title
            };
            //编辑
            if (data.treeId) {
                conf.data.pkId = data.treeId;
            }
            let self_ = this;
            Util.open(conf, async function (action) {
                if (action != "ok") {
                    return;
                }
                let pkId = this.resultData.treeId;
                let res = await SysTreeApi.getById(pkId,encodeURIComponent(JSON.stringify(self_.statisticConfig))) ;
                let row = res.data;
                switch (operator) {
                    case "add":
                        self_.categoryTree.addRoot(row, "name", "treeId");
                        break
                    case "edit":
                        for (let key in row){
                            data[key] =  row[key] ;
                        }
                        self_.treeData = [...self_.treeData];
                        break;
                    case "addchild":
                        if(parentData.hasOwnProperty('children') && Object.prototype.toString.call(parentData.children).indexOf('Array')>-1){
                            parentData.childAmount = parentData.childAmount + 1 ;
                            parentData.children.push(row)
                        }else {
                            parentData.childAmount = 1 ;
                            parentData['children'] = [row];
                        }
                        self_.treeData = [...self_.treeData];
                        break;
                    case "addSibling":
                        parentData.children.push(row);
                        self_.treeData = [...self_.treeData];
                        break;
                }
            });
        },
    }
}
</script>

<style scoped>
.tree-style>>>.rx-v-tree-trigger i{
    color: #666666;
}
.tree-style>>> .rx-icon-document i {
    color: #e3e3e3!important;
}
.tree-style>>>.rx-icon-container i{
    color:#FFDC53FF;
    font-size: 16px;
}
.tree-style>>>.rx-v-tree-content-active i{
    color: #4285f4!important;
}
.rx-vue-tree-box >>> .rx-expand-icon-box .rx-v-tree-icon{
    font-size: 13px!important;
    margin-left: 1px;
}
.rx-vue-tree-box >>> .rx-v-tree-icon{
    margin-top: 1px;
}
.rx-vue-tree-box >>> .rx-v-tree-icon-box{
    width: 16px;
}
.btn i{
    margin-right: 4px;
}
</style>